const dayjs = require('dayjs')
const URL = require('url')
const fs = require('fs-extra')
const path = require('path')

/**
 * 所有配置加载后，调用的动态配置
 */
const config = {}

// 上传存储目录
config.getUploadDir = (bucket = '') => {
  bucket = bucket ? `${bucket}/` : ''

  const uploadDir = '/uploads/' + bucket + dayjs().format('YYMMDD') + '/'
  return uploadDir
}

// 获取上传文件名
config.getUploadFilename = (originalname) => {
  const ext = originalname ? path.parse(originalname).ext : '.png'
  const filename = dayjs().format('HHmmss') + Math.random().toString().substr(2, 5) + ext
  return filename
}

// multer上传配置
config.multerStorage = (multer, remoteHost) => {
  const storage = multer.diskStorage({
    // 存放目录
    destination(req, file, cb) {
      // 桶
      const bucket = URL.parse(req.url, true).query.bucket

      // 文件上传目录
      const fileDir = config.getUploadDir(bucket)

      // 实际存储目录
      const destination = path.join(config.uploadDir, fileDir)

      fs.ensureDirSync(destination)

      file.fileDir = fileDir

      cb(null, destination)
    },
    filename(req, file, cb) {
      const { fileDir, destination } = file

      const filename = config.getUploadFilename(file.originalname)
      const domain = remoteHost || config.host

      // 路径是否加域名
      // const domain = '';

      file.domain = domain
      file.key = fileDir + filename
      file.url = domain + file.key

      cb(null, filename)
    },
  })

  return storage
}

module.exports = config
